﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sys.WebRes.Publish.Areas.Admin.Models;
using Sys.WebRes.Data;

namespace Sys.WebRes.Publish.Areas.Admin.Controllers
{
    public partial class ResourceController
    {
        /// <summary>
        /// 获取产品信息，或者新建产品信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult EditProduct(int? id)
        {
            var model = new ProductModel();
            if (id == null)
            {
                model.ResTypeID = ResType.Product.ID;
                model.StatusTypeID = ResStatusType.NotReviewed.ID;
                model.Sections = new List<SecResLinkModel> { new SecResLinkModel() };
            }
            else
            {
                using (var db = DB.New)
                {
                    model = GetResourceModel<ProductModel>((int)id, db);
                }
            }

            return View(model);
        }

        /// <summary>
        /// 保存产品信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditProduct(int? id, ProductModel model)
        {
            using (var tran = DB.NewTran)
            {
                using (var db = DB.New)
                {
                    SaveResource(db, id, model);

                    db.SaveChanges();
                }
                tran.Complete();
            }

            return RedirectToAction("EditProduct", new { id = model.ID });
        }

        /// <summary>
        /// 删除产品信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult DeleteProduct(int id)
        {
            using (var tran = DB.NewTran)
            {
                using (var db = DB.New)
                {
                    var res = DeleteResourceInfo(db, id, true);

                    db.SaveChanges();
                }
                tran.Complete();
            }

            return View(new ProductModel());
        }
    }
}